function varargout = GUI2(varargin)
% GUI2 M-file for GUI2.fig
%      GUI2, by itself, creates a new GUI2 or raises the existing
%      singleton*.
%
%      H = GUI2 returns the handle to a new GUI2 or the handle to
%      the existing singleton*.
%
%      GUI2('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in GUI2.M with the given input arguments.
%
%      GUI2('Property','Value',...) creates a new GUI2 or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before GUI2_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to GUI2_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help GUI2

% Last Modified by GUIDE v2.5 29-Oct-2010 16:59:55

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @GUI2_OpeningFcn, ...
                   'gui_OutputFcn',  @GUI2_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


%% --- Executes just before GUI2 is made visible.
function GUI2_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to GUI2 (see VARARGIN)

% Choose default command line output for GUI2
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);
if strcmp(get(hObject,'Visible'),'off')
    temp_image = imread('Under_Construction04.jpg');
    image(temp_image);
end
% UIWAIT makes GUI2 wait for user response (see UIRESUME)
% uiwait(handles.figure1);


%% --- Outputs from this function are returned to the command line.
function varargout = GUI2_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


%% --- Executes on button press in left.
function left_Callback(hObject, eventdata, handles)
% hObject    handle to left (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

%Update xlim and ylim values
handles.hrdata.xlimlow = handles.hrdata.xlimlow -3;
handles.hrdata.xlimup = handles.hrdata.xlimup -3;
main_menu_Callback(hObject, eventdata, handles);
% Update handles structure
guidata(handles.figure1, handles);

%% --- Executes on button press in right.
function right_Callback(hObject, eventdata, handles)
% hObject    handle to right (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

%Update xlim and ylim values
handles.hrdata.xlimlow = handles.hrdata.xlimlow +3;
handles.hrdata.xlimup = handles.hrdata.xlimup +3;
main_menu_Callback(hObject, eventdata, handles);
% Update handles structure
guidata(handles.figure1, handles);

%% --- Executes on selection change in popupmenu2.
function popupmenu2_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu2 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu2


%% --- Executes during object creation, after setting all properties.
function popupmenu2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenu2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

%% --- Executes on button press in deter_athlets.
function deter_athlets_Callback(hObject, eventdata, handles)
% hObject    handle to deter_athlets (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of deter_athlets

% Setting the tick-box value
% Max: On
% Min: Off
if get(hObject,'Value') == get(hObject,'Max')
   athlets = 1;
else
   athlets = 0;
end
% Saving object details
handles.hrdata.athlets = athlets;
%Update the heart condition
main_menu_Callback(hObject, eventdata, handles);
% Update handles structure
guidata(hObject,handles)


function age_Callback(hObject, eventdata, handles)
% hObject    handle to age (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of age as text
%        str2double(get(hObject,'String')) returns contents of age as a double

%Getting age in the text box
age = get(hObject, 'String');
%Changing age from string to numerical values
age = str2double(age);
%Update the heart condition
main_menu_Callback(hObject, eventdata, handles);
% Save the new filename
handles.hrdata.age = age;
guidata(hObject,handles)


%% --- Executes during object creation, after setting all properties.
function age_CreateFcn(hObject, eventdata, handles)
% hObject    handle to age (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


%% --- Executes on button press in update.
function update_Callback(hObject, eventdata, handles)
% hObject    handle to update (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

%Update the heart condition
main_menu_Callback(hObject, eventdata, handles);

%% --- Executes on button press in QRSdetect.
function QRSdetect_Callback(hObject, eventdata, handles)
% hObject    handle to QRSdetect (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
ecg_peaks(handles.hrdata.filtdata_sgo,handles.hrdata.xlimlow,...
          handles.hrdata.xlimup);


%% --- Executes on button press in timeline.

function timeline_Callback(hObject, eventdata, handles)
% hObject    handle to timeline (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
ecg_timeline(handles.hrdata.real_heartrate);

%% --- Executes on button press in history.
function history_Callback(hObject, eventdata, handles)
% hObject    handle to history (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
ecg_hist(handles.hrdata.real_heartrate);

%% --- Executes on button press in scatterplot.
function scatterplot_Callback(hObject, eventdata, handles)
% hObject    handle to scatterplot (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
ecg_scatter(handles.hrdata.real_heartrate);

%% --- Executes on button press in ecgplot.
function ecgplot_Callback(hObject, eventdata, handles)
% hObject    handle to ecgplot (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
ecgsave(handles.hrdata.filtdata_sgo);

%% --- Executes on button press in Load2.
function Load2_Callback(hObject, eventdata, handles)
% hObject    handle to Load2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

%Load Data
data = LoadData(handles.hrdata.filename,handles.hrdata.path);
%normalize ecg data
[v,t] = ecg_normalize(data);
%Storing filtered data
%[notch,cheby,sgo] = ecgfilt(data);
handles.hrdata.filtdata.data = data;
[sgo,notch,cheby] = ecg_filter(v);
%Filter data allocation
handles.hrdata.filtdata_stop = notch;
handles.hrdata.filtdata_cheby = cheby;
handles.hrdata.filtdata_sgo = sgo;
% Hiding filter
% filtering the ecg signal and only QRS peak exists
QRS_filt = ecg_smooth2(diff(sgo,1));
handles.hrdata.filtdata_QRS = QRS_filt;
%Setting xlim on axes display
xlimlow = 3;
xlimhigh = 6;
handles.hrdata.xlimlow = xlimlow;
handles.hrdata.xlimup = xlimhigh;
%Setting ylim on axes display (unfiltered signal)
ylimup = 65536;
ylimlow = 0;
handles.hrdata.ylimlow = ylimlow;
handles.hrdata.ylimup = ylimup;
%Setting ylim on axes display (filtered signal)
ylimup2 = 6;
ylimlow2 = -5;
handles.hrdata.ylimlow2 = ylimlow2;
handles.hrdata.ylimup2 = ylimup2;
%Average heartbeat calculation
[heartrate, Real_heartrate] = hrc(handles.hrdata.filtdata_QRS(5500:35000));
% Real-time heartrate with moving average filter smoothing
movavgECG = movavgecg(Real_heartrate);
% Compare heartrate with sgo data
[heartrate movavgECG] = comparehrc(sgo, heartrate, movavgECG);
if std(movavgECG) <= 2
    heartrate = mean(movavgECG);
else
    heartrate = median(movavgECG);
end
  
% Display parameters: heartrate
handles.hrdata.heartrate = heartrate;
handles.hrdata.real_heartrate = Real_heartrate;
heartrate_string = sprintf('%.2f',handles.hrdata.heartrate);
% Display maximum and minimum heartrate
[max_ecg,min_ecg,sd_ecg] = ecg_history(movavgECG);
max_ecg_string = sprintf('%.2f',max_ecg);
min_ecg_string = sprintf('%.2f',min_ecg);
sd_ecg_string = sprintf('%.2f',sd_ecg);

%Storing max,min and standard deviation of heartrate for analysis
handles.hrdata.maxHR = max_ecg;
handles.hrdata.minHR = min_ecg;
handles.hrdata.sdHR = sd_ecg;

%Setting heartrate
set(handles.heartrate, 'String', heartrate_string);
set(handles.max_ecg, 'String', max_ecg_string);
set(handles.min_ecg, 'String', min_ecg_string);
set(handles.sd_ecg, 'String', sd_ecg_string);
%Setting default patient setting
handles.hrdata.age = 15;
handles.hrdata.athlets = 0;
%Run main menu setting (default)
main_menu_Callback(hObject, eventdata, handles);
% Save the filtered data
guidata(hObject,handles)

%% --- Executes on selection change in main_menu.
function main_menu_Callback(hObject, eventdata, handles)
% hObject    handle to main_menu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') throw(exception); s main_menu contents as cell array
%        contents{get(hObject,'Value')} throw(exception); s selected item
%        from main_menu
transform_data = sgotransform(handles.hrdata.filtdata.data,...
                              handles.hrdata.filtdata_sgo);
ecgplot(transform_data,handles.hrdata.xlimlow,handles.hrdata.xlimup,...
        handles.hrdata.ylimlow2,handles.hrdata.ylimup2);
msg = diag_msg(handles.hrdata.heartrate,handles.hrdata.age,handles.hrdata.athlets,...
               handles.hrdata.sdHR);
set(handles.disease, 'String', msg);


%% --- Executes on button press in browse.
function browse_Callback(hObject, eventdata, handles)
% hObject    handle to browse (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

%Getting filename
[filename,path] = uigetfile('*.bin');
%Storing filename
handles.hrdata.filename = filename;
handles.hrdata.path = path;
set(handles.browse_msg, 'String', filename);
%Save the filename
guidata(hObject,handles)

%% --- Executes on button press in reset2.
function reset2_Callback(hObject, eventdata, handles)
% hObject    handle to reset2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
initialize_gui(gcbf, handles, true);

%--------------------------------------------------------------------%
% If the hrdata field is present and the reset flag is false, it means
% we are we are just re-initializing a GUI by calling it from the cmd line
% while it is up. So, bail out as we dont want to reset the data.
function initialize_gui(fig_handle, handles, isreset)
if isfield(handles, 'hrdata') && ~isreset
    return
end

handles.hrdata.age = 0;
handles.hrdata.oxy  = 0;
handles.hrdata.mov_switch = 0;
handles.hrdata.athlets = 0;

set(handles.deter_athlets,'Value',0);
set(handles.browse_msg, 'String', 'Press the Browse Button!');
set(handles.heartrate,  'String', '0');
set(handles.max_ecg, 'String', '0');
set(handles.min_ecg, 'String', '0');
set(handles.sd_ecg, 'String', '0');
set(handles.disease, 'String', 'No signals');
temp_image = imread('Under_Construction04.jpg');
image(temp_image);

% Update handles structure
guidata(handles.figure1, handles);


%% --- Executes on button press in save.
function save_Callback(hObject, eventdata, handles)
% hObject    handle to save (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

v = handles.hrdata.filtdata_sgo;
v = double(v);
t = (0:(length(v)-1))/553.6;

current_dir=cd;
[filename,path,idx] = uiputfile(...
       {'*.xls','Excel file (*.xls)';
       '*.pdf','PDF file (*.pdf)';
       '*.png','Image file (*.png)';
       '*.json','Javascript Object file (for file upload) (*.json)'},...
       'Save As...');
 
   switch idx
       case 1
           cd(path);
           xlswrite(filename,horzcat(t',v));
       case 2
           cd(path);
           orient portrait;
           print('-dpdf',filename);
       case 3
           cd(path);
           orient portrait;
           print('-dpng',filename);
       case 4
           save_json(filename,path,t,v);
   end
   cd(current_dir);
   


%% --- Executes on button press in link.
function link_Callback(hObject, eventdata, handles)
% hObject    handle to link (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
web 'www.ipscg2010.com' -new;


%% --- Executes on button press in inverted.
function inverted_Callback(hObject, eventdata, handles)
% hObject    handle to inverted (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of inverted
%Filter data allocation
handles.hrdata.filtdata_sgo = -1*handles.hrdata.filtdata_sgo;
% Hiding filter
% filtering the ecg signal and only QRS peak exists
QRS_filt = diff(handles.hrdata.filtdata_sgo,1).*100;
handles.hrdata.filtdata_QRS = QRS_filt;
%Setting xlim on axes display
xlimlow = 3;
xlimhigh = 6;
handles.hrdata.xlimlow = xlimlow;
handles.hrdata.xlimup = xlimhigh;

%Average heartbeat calculation
[heartrate, Real_heartrate] = hrc(handles.hrdata.filtdata_QRS);
movavgECG = movavgecg(Real_heartrate);
[heartrate movavgECG] = comparehrc(handles.hrdata.filtdata_sgo,...
                                   heartrate, movavgECG);
if std(movavgECG) <= 2
    heartrate = mean(movavgECG);
else
    heartrate = median(movavgECG);
end
handles.hrdata.heartrate = heartrate;
handles.hrdata.real_heartrate = Real_heartrate;
heartrate_string = sprintf('%.2f',handles.hrdata.heartrate);

[max_ecg,min_ecg,sd_ecg] = ecg_history(movavgECG);
max_ecg_string = sprintf('%.2f',max_ecg);
min_ecg_string = sprintf('%.2f',min_ecg);
sd_ecg_string = sprintf('%.2f',sd_ecg);

%Storing max,min and standard deviation of heartrate for analysis
handles.hrdata.maxHR = max_ecg;
handles.hrdata.minHR = min_ecg;
handles.hrdata.sdHR = sd_ecg;

%Setting heartrate
set(handles.heartrate, 'String', heartrate_string);
set(handles.max_ecg, 'String', max_ecg_string);
set(handles.min_ecg, 'String', min_ecg_string);
set(handles.sd_ecg, 'String', sd_ecg_string);
%Setting default patient setting
handles.hrdata.age = 15;
handles.hrdata.athlets = 0;
%Run main menu setting (default)
main_menu_Callback(hObject, eventdata, handles);
% Save the filtered data
guidata(hObject,handles)


%% --- Executes on button press in minus_mag.
function minus_mag_Callback(hObject, eventdata, handles)
% hObject    handle to minus_mag (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
sens1 = 5000;
sens2 = 0.5;
handles.hrdata.ylimlow = handles.hrdata.ylimlow - sens1;
handles.hrdata.ylimup = handles.hrdata.ylimup + sens1;
handles.hrdata.ylimlow2 = handles.hrdata.ylimlow2 - sens2;
handles.hrdata.ylimup2 = handles.hrdata.ylimup2 + sens2;
main_menu_Callback(hObject, eventdata, handles);
% Update handles structure
guidata(handles.figure1, handles);


%% --- Executes on button press in in_mag.
function in_mag_Callback(hObject, eventdata, handles)
% hObject    handle to in_mag (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
sens1 = 5000;
sens2 = 0.5;
handles.hrdata.ylimlow = handles.hrdata.ylimlow + sens1;
handles.hrdata.ylimup = handles.hrdata.ylimup - sens1;
handles.hrdata.ylimlow2 = handles.hrdata.ylimlow2 + sens2;
handles.hrdata.ylimup2 = handles.hrdata.ylimup2 - sens2;
main_menu_Callback(hObject, eventdata, handles);
% Update handles structure
guidata(handles.figure1, handles);